package com.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.common.utils.UuidUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;
import com.gulimall.product.dao.CategoryDao;
import com.gulimall.product.entity.CategoryEntity;
import com.gulimall.product.service.CategoryBrandRelationService;
import com.gulimall.product.service.CategoryService;
import com.gulimall.product.vo.web.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redisson;

    //使用springcachce实现
    @Cacheable(value = {"category"},key = "#root.method.name",sync = true)
    @Override
    public Map<Object, List<Catelog2Vo>> getCatalogJson() {
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        Map<Object, List<Catelog2Vo>> catavos = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、每一个的1级的分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            //2、封装2级分类
            List<Catelog2Vo> collect = null;
            if (categoryEntities != null) {
                collect = categoryEntities.stream().map(item -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, item.getCatId().toString(), item.getName().toString());
                    //封装3级分类
                    //每一个二级的分类
                    List<CategoryEntity> categoryEntities2 = getParent_cid(selectList, item.getCatId());
                    List<Catelog2Vo.Catelog3Vo> collect3 = null;
                    if (categoryEntities2 != null) {
                        collect3 = categoryEntities2.stream().map(item2 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(item2.getParentCid().toString()
                                    , item2.getCatId().toString(), item2.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                    }
                    catelog2Vo.setCatalog3List(collect3);
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return collect;
        }));
        return catavos;
    }

    //@Override
    public Map<Object, List<Catelog2Vo>> getCatalogJson2() {
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            //2、缓存里无数据
            Map<Object, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedisLock();
            String catalog = JSON.toJSONString(catalogJsonFromDb);
            catalogJSON = catalog;
        }
        //转为指定的对象
        Map<Object, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<Object, List<Catelog2Vo>>>() {
        });
        return result;
    }

    //Redisson分布式锁实现
    public Map<Object, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock() {
        RLock lock = redisson.getLock("catalogJson-lock");
        lock.lock();
        Map<Object, List<Catelog2Vo>> catavos = null;
        try {
            catavos = getDataFromDb();
        } finally {
            lock.unlock();
        }
        return catavos;
    }

    //分布式锁(redis的nx实现)
    public Map<Object, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() {
        String uuid = UuidUtils.generateUuid();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.MILLISECONDS);
        if (lock) {
            Map<Object, List<Catelog2Vo>> catavos = null;
            try {

                catavos = getDataFromDb();
            } finally {
                //释放锁，要保证释放锁原子性
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                Long execute = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock", uuid));

            }
            return catavos;

        } else {
            return getCatalogJsonFromDbWithRedisLock();  //回旋调用
        }

    }

    //对此方法进行改良，从遍历查数据库到一次性查出数据再进行逻辑到存入到redis
    public Map<Object, List<Catelog2Vo>> getDataFromDb() {
        /**
         * 1、将数据库的多次查询变为一次（查出所有的数据，再去进行对比查找）
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        Map<Object, List<Catelog2Vo>> catavos = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、每一个的1级的分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            //2、封装2级分类
            List<Catelog2Vo> collect = null;
            if (categoryEntities != null) {
                collect = categoryEntities.stream().map(item -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, item.getCatId().toString(), item.getName().toString());
                    //封装3级分类
                    //每一个二级的分类
                    List<CategoryEntity> categoryEntities2 = getParent_cid(selectList, item.getCatId());
                    List<Catelog2Vo.Catelog3Vo> collect3 = null;
                    if (categoryEntities2 != null) {
                        collect3 = categoryEntities2.stream().map(item2 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(item2.getParentCid().toString()
                                    , item2.getCatId().toString(), item2.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                    }
                    catelog2Vo.setCatalog3List(collect3);
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return collect;
        }));
        String catalog = JSON.toJSONString(catavos);
        redisTemplate.opsForValue().set("catalogJSON", catalog);
        return catavos;
    }

    /**
     *
     */
    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> {
            return item.getParentCid() == cid;
        }).collect(Collectors.toList());
        //return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
        return collect;
    }


    //Cacheable 注解开发：缓存方法结果


    @Cacheable(value = {"category"},key = "#root.method.name",sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.组装成父子的树形结构
        //2.1)找到所有的一级分类
        List<CategoryEntity> leve1Menus = entities.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == 0;
        }).map((menu) -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {  //排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return leve1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 当前删除的菜单是否被别的地方引用
        //一般进行逻辑删除，一个字段表示是否被删除
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 根据当前id返回当前节点的完整路径
     *
     * @param attrGroupId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long attrGroupId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parents = getParentCid(attrGroupId, paths);
        Collections.reverse(parents);
        return parents.toArray(new Long[parents.size()]);
    }


    //CacheEvict 当进行更新操作,将缓存里的数据删除

    @Caching(evict = {
            @CacheEvict(key = "'getLevel1Categorys'"),
            @CacheEvict(key = "'getCatalogJson'")
    })
    @Transactional
    @Override
    public void updateDetail(CategoryEntity category) {
        //同时修改关联到的表
        this.updateById(category);
        if (!StringUtils.isEmpty(category.getName())) {
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
            //TODO 其它关联
        }
    }

    /**
     * 找到当前菜单的路径
     *
     * @param attrGroupId 当前菜单id
     * @return
     */
    private List<Long> getParentCid(Long attrGroupId, List<Long> paths) {
        paths.add(attrGroupId);
        CategoryEntity categoryEntity = this.getById(attrGroupId);
        if (categoryEntity.getParentCid() != 0) {
            getParentCid(categoryEntity.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 找到当前菜单的子菜单
     *
     * @param root 当前菜单
     * @param all  所有菜单
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //1、找到子菜单，递归找法
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //2、排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }
}